// pages/cart/component/cart.js
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { userStore } from '@/store/userStore'
import { addCart, getCartList, updateChecked, getIsCheckedAll, deleteGoods } from '@/api/cart'
import { debounce } from 'miniprogram-licia'
import { swipeCell } from '@/behaviors/swipeCell'
const computedBehavior = require('miniprogram-computed').behavior
ComponentWithStore({
  behaviors: [computedBehavior,swipeCell],
  storeBindings:{
    store: userStore,
    fields: ['token']
  },
  // 组件的初始数据
  data: {
    cartList: [],
    emptyDes: '还没有添加商品，快去添加吧～'
  },
  computed: {
    CheckedAll(data){
      return data.cartList.length !== 0
      && data.cartList.every(item => item.isChecked === 1)
    },
    TotalPrice(data){
      let totalPrice = 0
      data.cartList.forEach(item => {
        if(item.isChecked){
          totalPrice += item.count * item.price
        }
      })
      return totalPrice
    }
  },
  // 组件的方法列表
  methods: {
    async showTipGetList(){
      if(!this.data.token){
        this.setData({
          emptyDes: "您尚未登录，点击登录获取更多权益",
          cartList: []
        })
        return
      }
      const { code, data:cartList } = await getCartList()
      if(code === 200){
        this.setData({
          cartList,
          emptyDes: cartList.length === 0 && '还没有添加商品，快去添加吧~'
        })
      }
    },
    async updateChecked(e){
      const { id, index } = e.target.dataset
      const isChecked = e.detail ? 1 : 0
      const { code } = await updateChecked(id,isChecked)
      if(code === 200){
        // this.showTipGetList()
        this.setData({
          [`cartList[${index}].isChecked`]: isChecked
        })
      }
    },
    async checkedStatus(e){
      const isChecked = e.detail ? 1 : 0
      const { code } = await getIsCheckedAll(isChecked)
      if(code === 200){
        // this.showTipGetList()
        const newCartList = JSON.parse(JSON.stringify(this.data.cartList))
        newCartList.forEach(item => item.isChecked = isChecked)
        this.setData({
          cartList: newCartList
        })
      }
    },
    changeBuyNum: debounce(async function(e){
      const newBuyNum = e.detail > 999? 999 : e.detail
      const { id, index, oldbuynum } = e.target.dataset
      // /^([1-9]|[1-9]\d|1\d{2}|200)$/
      const reg = /^[1-9]?\d{0,2}$/
      const regRes = reg.test(newBuyNum)
      console.log(regRes)
      if(!regRes){
        this.setData({
          [`cartList[${index}].count`]: oldbuynum
        })
        return
      }
      const disCount = newBuyNum - oldbuynum
      if(disCount===0) return
      const { code } = await addCart({goodsId:id,count:disCount})
      if(code === 200){
        this.setData({
          [`cartList[${index}].count`]: newBuyNum,
          [`cartList[${index}].isChecked`]: 1
        })
      }
    },500),
    async delCartGoods(e){
      const { id } = e.target.dataset
      const modalRes = wx.modal({content: '您确认删除该商品吗？'})
      if(modalRes){
        await deleteGoods(id)
        this.showTipGetList()
      }
    },
    toOrder(){
      if(this.data.TotalPrice === 0){
        wx.toast({title: "请选择需要购买的商品"})
        return
      }
      wx.navigateTo({
        url: '/modules/orderPayModule/pages/order/detail/detail',
      })
    },
    onShow(){
      this.showTipGetList()
    },
    onhide(){
      this.onSwipeCellCommonClick()
    }
  }
})
